//package com.topcent.tioxyc.consumer;
//
//import cn.hutool.json.JSONArray;
//import cn.hutool.json.JSONObject;
//import cn.hutool.json.JSONUtil;
//import com.rabbitmq.client.Channel;
//import com.topcent.tioxyc.constants.KeyConstant;
//import com.topcent.tioxyc.pojo.*;
//import com.topcent.tioxyc.util.ApiClient;
//import com.topcent.tioxyc.util.ConnmeUtils;
//import com.topcent.tioxyc.util.PurchaseCommunity;
//import lombok.extern.slf4j.Slf4j;
//import org.apache.http.Header;
//import org.springframework.amqp.core.Message;
//import org.springframework.amqp.rabbit.annotation.RabbitHandler;
//import org.springframework.amqp.rabbit.annotation.RabbitListener;
//import org.springframework.stereotype.Component;
//import org.springframework.web.bind.annotation.GetMapping;
//
//import java.io.IOException;
//import java.math.RoundingMode;
//import java.math.BigDecimal;
//import java.util.ArrayList;
//import java.util.HashMap;
//import java.util.List;
//import java.util.Map;
//
///**
// * @author: weidian
// * @date: 2024/9/28 16:21
// * @Description: 这是一个付款单的消费类
// */
//@Slf4j
//@Component
//@RabbitListener(queues = "queue_c",concurrency = "1-1")
//public class FuKuanDanConsumer {
//
//    private static final String DATA_CREATE = "data_create";
//    private static final String DATA_UPDATE = "data_update";
//    private static final String DATA_DELETE = "data_remove";
//
//    @RabbitHandler
//    public void handleMessage(String msg, Channel channel, Message message) throws IOException {
//        try {
//            // 处理 payload 消息
//            System.out.println("Received payload: " + msg);
//            // 在这里执行具体的业务逻辑
//
//            // 在这里处理推送来的数据
//            JSONObject payloadJSON = JSONUtil.parseObj(msg);
//            String op = payloadJSON.getStr("op");
//            String data = payloadJSON.getStr("data");
//
//            if (DATA_UPDATE.equals(op)) {
//                create(data);
//                update(data);
//            }
//            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
//            System.out.println("Message acknowledged");
//        } catch (Exception e) {
//            // 处理异常并拒绝消息
//            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
//            System.err.println("付款单发送消息失败，重试中 " + e.getMessage());
//        }
//    }
//
//    private void update(String data) {
//        PaymentForm paymentForm = JSONUtil.toBean(data, PaymentForm.class);
//        Header[] headers = ConnmeUtils.createHeaders();
//        Map<String, Object> parameterDelete = new HashMap<>();
//        parameterDelete.put("instance_id", paymentForm.get_id());
//        parameterDelete.put("tasks_type", 1);
//        String jsonSale = JSONUtil.toJsonStr(parameterDelete);
//        JSONObject jdySale = ApiClient.sendPostRequest("https://api.jiandaoyun.com/api/v4/workflow/instance/get", headers, jsonSale);
//        JdyPurchaseOrder jdyPurchaseOrder = JSONUtil.toBean(jdySale, JdyPurchaseOrder.class);
//        if (jdyPurchaseOrder.getStatus() == 1) {
//            Map<String, Object> parameterCxv = new HashMap<>();
//            parameterCxv.put("app_id", "66a0c3efcd4dd2a1c8a4a13f");
//            parameterCxv.put("entry_id", "66a3727ee9d0a8542c969091");
//            for (PaymentForm.OrderFinalPayment orderFinalPayment : paymentForm.get_widget_1721548605263()) {
//                if (orderFinalPayment.get_widget_1727334556949() == null || orderFinalPayment.get_widget_1727334556949().isEmpty() ||
//                        orderFinalPayment.get_widget_1721548605264() == null || orderFinalPayment.get_widget_1721548605264().isEmpty()
//                || orderFinalPayment.get_widget_1721548605265()==null ) {
//                    continue; // 跳过当前遍历
//                }
//                HashMap<String, String> communti = new HashMap<>();
//                communti.put("_widget_1727315685608", orderFinalPayment.get_widget_1727334556949());
//                communti.put("_widget_1721987711273", orderFinalPayment.get_widget_1721548605264());
//                List<InvoiceDocument> invoiceDocuments = PurchaseCommunity.queryBased(parameterCxv, headers, communti, InvoiceDocument.class);
//                if (invoiceDocuments == null || invoiceDocuments.isEmpty()) {
//                    continue; // 跳过当前遍历
//                }
//
//
//                // 获取尾款占比
//                BigDecimal finalPaymentRate = BigDecimal.valueOf(orderFinalPayment.get_widget_1721548605265());
//
//                // 定义变量用于存储分摊金额总和和未付金额总和
//                BigDecimal totalAllocationAmount = BigDecimal.ZERO;
//                BigDecimal totalUnpaidAmount = BigDecimal.ZERO;
//                BigDecimal totalBalanceAmount = BigDecimal.ZERO;
//                InvoiceDocument document = invoiceDocuments.getFirst();
//                for (InvoiceDocument.InvoiceLineItem invoiceLineItem : document.get_widget_1727340673732()) {
//                    //把其他采购订单的付款金额拿过来。
//                    Map<String, Object> cgdd = new HashMap<>();
//                    cgdd.put("app_id", "6690c7633df0f4b90b4ef551");
//                    cgdd.put("entry_id", "669df675b02f2a74e35ca2f9");
//
//                    communti.put("_widget_1721628277543", invoiceLineItem.get_widget_1727340673739());
//                    communti.put("_widget_1721628277558", invoiceLineItem.get_widget_1727340673735());
//                    List<SAPPurchaseOrder> sapPurchaseOrders = PurchaseCommunity.queryBased(cgdd, headers, communti, SAPPurchaseOrder.class);
//                    if (sapPurchaseOrders.isEmpty() || sapPurchaseOrders.getFirst() == null ||
//                            sapPurchaseOrders.getFirst().get_widget_1724225500094() == null) {
//                        continue;
//                    }
//
//
//                    // 如果采购订单查询结果不为空，取出已付金额
//                    BigDecimal paidAmount = sapPurchaseOrders.isEmpty()
//                            ? BigDecimal.ZERO
//                            : BigDecimal.valueOf(sapPurchaseOrders.getFirst().get_widget_1722475785243());
//
//                    // 计算分摊金额
//                    BigDecimal allocationAmount = invoiceLineItem.get_widget_1727340673745()
//                            .multiply(finalPaymentRate)
//                            .setScale(10, RoundingMode.HALF_UP);
//
//                    // 如果原分摊字段有数据，累加现有值；否则直接写入
//                    BigDecimal existingAllocationAmount = invoiceLineItem.get_widget_1731575068806();
//                    if (existingAllocationAmount != null) {
//                        allocationAmount = allocationAmount.add(existingAllocationAmount);
//                    }
//                    invoiceLineItem.set_widget_1731575068806(allocationAmount);
//
//                    // 计算未付金额
//                    BigDecimal zongshu = invoiceLineItem.get_widget_1727340673745().add(sapPurchaseOrders.getFirst().get_widget_1724225500094());
//
//                    BigDecimal unpaidAmount = zongshu
//                            .subtract(allocationAmount)
//                            .subtract(paidAmount)
//                            .setScale(10, RoundingMode.HALF_UP);
//
//                    invoiceLineItem.set_widget_1731575068807(unpaidAmount);
//
//
//                    // 计算分摊总金额累加值：已付金额减去未付金额，加上当前行的分摊金额
//                    BigDecimal allocationAdjustment = paidAmount
//                            .add(allocationAmount);
//
//                    // 累加到分摊金额总和和未付金额总和
//                    totalAllocationAmount = totalAllocationAmount.add(allocationAdjustment);
//                    totalUnpaidAmount = totalUnpaidAmount.add(unpaidAmount);
//                    totalBalanceAmount = totalBalanceAmount.add(invoiceLineItem.get_widget_1727340673745().subtract(allocationAmount));
//                }
//
//                // 输出分摊金额总和和未付金额总和到总记录
//                BigDecimal existingTotalAllocationAmount = invoiceDocuments.getFirst().get_widget_1731638214169();
//                BigDecimal existingTotalUnpaidAmount = invoiceDocuments.getFirst().get_widget_1731638214170();
//
//                if (existingTotalAllocationAmount != null) {
//                    totalAllocationAmount = totalAllocationAmount.add(existingTotalAllocationAmount);
//                }
//                if (existingTotalUnpaidAmount != null) {
//                    totalUnpaidAmount = totalUnpaidAmount.add(existingTotalUnpaidAmount);
//                }
//
//                invoiceDocuments.getFirst().set_widget_1731638214169(totalAllocationAmount);
//                invoiceDocuments.getFirst().set_widget_1731638214170(totalUnpaidAmount);
//                invoiceDocuments.getFirst().set_widget_1731915520417(totalBalanceAmount);
//
//
//                Map<String, Object> parameterInster = new HashMap<>();
//                parameterInster.put("app_id", "66a0c3efcd4dd2a1c8a4a13f");
//                parameterInster.put("entry_id", "66a3727ee9d0a8542c969091");
//                parameterInster.put("is_start_trigger", "true");
//                parameterInster.put("data_id", invoiceDocuments.getFirst().get_id());
//                invoiceDocuments.getFirst().set_id(null);
//                parameterInster.put("data", ConnmeUtils.convertEntityToMapNull(invoiceDocuments.getFirst()));
//                String jsonSalee = JSONUtil.toJsonStr(parameterInster);
//                log.info("Modified sales order prepayment: {}", jsonSale);
//                ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/update", headers, jsonSalee);
//            }
//        }
//    }
//
//
//    private void create(String data) {
//        Header[] headers = ConnmeUtils.createHeaders();
//        Fukuandan fukuandan = JSONUtil.toBean(data, Fukuandan.class);
//        if (fukuandan.getFlowState() != 1 || fukuandan.get_widget_1721546510495()==null) {
//            return;
//        }
//        Map<String, Map<String, Double>> yushou = new HashMap<>();
//
//        for (Fukuandan.Yufu yufu : fukuandan.get_widget_1721546510495()) {
//            if (yushou.containsKey(yufu.get_widget_1721546510504())) {
//                Map<String, Double> stringDoubleMap = yushou.get(yufu.get_widget_1721546510504());
//                if (stringDoubleMap.containsKey(yufu.get_widget_1721616942683())) {
//                    Double aDouble = yushou.get(yufu.get_widget_1721546510504()).get(yufu.get_widget_1721616942683());
//                    stringDoubleMap.put(yufu.get_widget_1721616942683(), yufu.get_widget_1721546510520() + aDouble);
//                } else {
//                    stringDoubleMap.put(yufu.get_widget_1721616942683(), yufu.get_widget_1721546510520());
//                }
//
//            } else {
//                Map<String, Double> yushou001 = new HashMap<>();
//                yushou001.put(yufu.get_widget_1721616942683(), yufu.get_widget_1721546510520());
//                yushou.put(yufu.get_widget_1721546510504(), yushou001);
//            }
//        }
//        chuliYuSuan(headers, yushou);
//    }
//
//    private void chuliYuSuan(Header[] headers, Map<String, Map<String, Double>> weikuan) {
//        weikuan.forEach((key, innerMap) -> {
//            try {
//                Map<String, Object> parameterCxv = new HashMap<>();
//                parameterCxv.put("app_id", "6690c7633df0f4b90b4ef551");
//                parameterCxv.put("entry_id", "669df675b02f2a74e35ca2f9");
//
//                log.info("Processing innerMap: " + innerMap);
//                innerMap.forEach((innerKey, value) -> {
//                    HashMap<String, String> communti = new HashMap<>();
//
//                    communti.put("_widget_1721628277543", key);
//                    communti.put("_widget_1721628277558", innerKey);
//                    List<SAPPurchaseOrder> sapPurchaseOrders = PurchaseCommunity.queryBased(parameterCxv, headers, communti, SAPPurchaseOrder.class);
//                    log.info("Processing inner key: " + innerKey + ", value: " + value);
//                    SAPPurchaseOrder salesOrderKu = sapPurchaseOrders.get(0);
//                    if (salesOrderKu == null) {
//                        log.error("SalesOrderKu is null for key: " + key);
//                        return;
//                    }
//
//                    if (sapPurchaseOrders.getFirst().get_widget_1722475785243() != null) {
//                        sapPurchaseOrders.getFirst().set_widget_1722475785243(sapPurchaseOrders.getFirst().get_widget_1722475785243() + value);
//                    } else {
//                        sapPurchaseOrders.getFirst().set_widget_1722475785243(value);
//                    }
//                    BigDecimal subtract = sapPurchaseOrders.getFirst().get_widget_1724225500094().subtract(BigDecimal.valueOf(sapPurchaseOrders.getFirst().get_widget_1722475785243()));
//                    sapPurchaseOrders.getFirst().set_widget_1731911494439(subtract);
//
//                    Map<String, Object> parameterInster = new HashMap<>();
//                    parameterInster.put("app_id", "6690c7633df0f4b90b4ef551");
//                    parameterInster.put("entry_id", "669df675b02f2a74e35ca2f9");
//                    parameterInster.put("is_start_trigger", "true");
//                    parameterInster.put("data_id", sapPurchaseOrders.getFirst().get_id());
//                    sapPurchaseOrders.getFirst().set_id(null);
//                    parameterInster.put("data", ConnmeUtils.convertEntityToMapNull(sapPurchaseOrders.getFirst()));
//                    String jsonSale = JSONUtil.toJsonStr(parameterInster);
//                    log.info("Modified sales order prepayment: " + jsonSale);
//                    ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/update", headers, jsonSale);
//
//                });
//
//            } catch (Exception e) {
//                log.error("Error processing key: {}", key, e);
//            }
//        });
//
//
//    }
//
//
//}
